/*******************************************************************************
 * Fotogallery creata con jQuery.
 * Plugin jQuery.
 * 
 * @author      Mattia Leonardo Angelillo
 * @email       mattia.angelillo@gmail.com
 * @date        06/12/2014
 * @version     1.0.0 beta
 * @description Possibilità di creare una galleria fotografica selezionando
 *              le foto dagli album di Picasa.
 *              Nel caso si usi il menu con Picasa si richiamano tutti gli 
 *              album dell'account inserito e cliccando su uno di essi si 
 *              esegue l'album selezionato.
*******************************************************************************/

(function( $ ) {
    //Configurazioni globali
    var container           = "#gioiagallery";
    var container_images    = "#gioiagallery .images";
    var container_image     = "#gioiagallery .images div";
    //var container_img       = "#gioiagallery .images div img";
    var container_img_width_this  = null;
    var container_img_height_this = null;
    var container_commands  = "#gioiagallery .commands";
    var container_count     = "#gioiagallery .info .count";
    var container_size      = "#gioiagallery .info .total";
    
    var thumbnail        = "#gioiagallery .thumbnail";
    var prev             = "#gioiagallery .commands .prev";
    var next             = "#gioiagallery .commands .next";
    
    /*Variabili del menu*/
    var menu             = "#gioiagallery .menu";
    var menu_menu        = "#gioiagallery .menu .menu";
    var menu_toggle      = "#gioiagallery .menu .toggle";
    
    var loaded           = false;
    var size             = 0;
    var fullscreen       = false;
    
    
    var gallery = "<div id='gioiagallery'>"+
            "<div class='title'></div>"+

            "<div class='menu'></div>"+

            "<div class='images'></div>"+

            "<div class='commands'>"+
                "<div class='prev'></div>"+
                "<div class='next'></div>"+
            "</div>"+

            "<div class='info'>"+
                "<span class='count'></span>/<span class='total'></span>"+
            "</div>";

            "<div class='thumbnail'>"+
            "</div>"+
          "</div>";
    
    /*==================================================
     * ACCEDO A PICASA PER OTTENERE LE IMMAGINI VOLUTE
     =================================================*/
    function picasa(username, album, settings, gallery, _this){
        fullscreen          = (settings.style.fullscreen==true)?true:false;
        var protocol            = document.location.protocol == 'http:' ? 'http:' : 'https:';
        var start               = (settings.start==0)?0:settings.start;
        var position            = start;
        var img_width           = 0;
        var imgContainer_width  = 0;
        
        //var album = settings.picasa.album;
        var url = protocol + '//picasaweb.google.com/data/feed/api/user/' + username + '/album/' + album + '?kind=photo&alt=json';
        
        $.ajax({
            dataType : 'json',
            url      : url,
            data     : 'callback=?',
            async    : false
        }).done(function (json){

            //$('body').append(gallery);
            $(_this).replaceWith(gallery);
            
            $("#gioiagallery .title").text(json.feed.title.$t);
            
            //Immagini
            for(i = 0; i < json.feed.entry.length; i++) {
                var summary = json.feed.entry[i].summary.$t;
                var img_src = json.feed.entry[i].content.src.split('/');
                var img_filename = img_src.pop();
                var img_src = img_src.join('/');
                var screen_width = $(window).width();
                
                html =  "<div>"+
                            "<img "+
                            " src='"+
                            img_src+'/s'+img_filename+
                            "'"+
                            " />"+
                            "</div>";
                
                size ++;
                
                $(container_images).append(html);
            }
            
            $(container_image).hide();
            $(container_image+':nth-child('+(position+1)+')').show();
            $(container_image+':nth-child('+(position+1)+') img').addClass('this');

            
            //Aggiungo a video il numero dell'immagine visualizzata e il numero totale
            $(container_count).text(position+1);
            $(container_size).text(size);
            
            //Prev
            if(position==0){$(prev).hide();}
            //Next
            if(position==size-1){$(next).hide();}
            
            
            img_fullscreen(fullscreen);
            
            
            
            //Aggiunta del menu
            var element = "<div class='toggle'>"+
                    "<div></div>"+
                    "<div></div>"+
                    "<div></div>"+
                    "</div>"+
                    
                    "<div class='menu'></div>";
            $('.menu',container).append(element).css({
                /*position : 'absolute',
                top      : '10px',
                right    : '10px'*/
            });
            
            
            //Aggiunta degli album come voce di menu
            var url = protocol + '//picasaweb.google.com/data/feed/api/user/' + username + '?kind=album&access=public&alt=json';
            $.getJSON(url, 'callback=?', $.proxy(function(json){
                for(var i = 0; i < json.feed.entry.length; i++) {
                    var album_title = json.feed.entry[i].title.$t;
                    var album       = json.feed.entry[i].title.$t.replace(/\'/g, "").replace(/\ /g, "").replace(/\-/g, "");
                    var album_link  = "callback=?";
                    /*var album_link = '#';
                    
                    for(var j = 0; j < json.feed.entry[i].link.length; j++) {
                        if (json.feed.entry[i].link[j].type == 'text/html'){
                            album_link = json.feed.entry[i].link[j].href;
                        }
                    }*/
                    
                    var img_src = json.feed.entry[i].media$group.media$content[0].url.split('/');
                    var img_filename = img_src.pop();
                    var img_src = img_src.join('/');
                    
                    html = "<div class='row'>"+
                                "<div class='album'>"+
                                    //"<a href='"+album_link+"'>"+album_title+"</a>"+
                                    "<a href='"+album_link+"' data-action='click' data-album='"+album+"' >"+album_title+"</a>"+
                                "</div>"+
                            "</div>";
                    
                    $(menu_menu).append(html);
                    
                    img_fullscreen(fullscreen);
                }
                
                
                /*======================
                 * EVENTI
                ======================*/
                //CLICK PER VISUALIZZARE IL NUOVO ALBUM
                $('[data-action=\'click\']').click(function (event){
                    event.preventDefault();
                    
                    //Richiamo il nuovo album di picasa
                    getAlbum(username, $(this).attr('data-album'), settings, gallery);
                });
            }));
            
            
            
            //CSS
            /*
            colors(settings.style.bgColor, settings.style.color);
            sizes(settings.style.width, settings.style.height);
            shadows(settings.shadow.h, settings.shadow.v, settings.shadow.color, settings.shadow.spread, settings.shadow.blur);
            */
            
            
            //PREV BUTTON
            $(prev).bind('click', function (){
                $(next).show();

                if(position != 0){
                    if(position == 1){
                        $(prev).hide();
                    }

                    position --;

                    $(container_image).hide();
                }
                
                $(container_count).text(position+1);
                $(container_image+':nth-child('+(position)+') img').removeClass('this');
                $(container_image+':nth-child('+(position+1)+') img').addClass('this');
                $(container_image+':nth-child('+(position+1)+')').show();
                
                img_fullscreen(fullscreen);
                
                /*if(fullscreen){positions();}
                sizes(settings.style.width, settings.style.height);*/
            });
            
            //NEXT BUTTON
            $(next).bind('click', function (){
                $(prev).show();

                if(position != size-1){
                    if(position == size-2){
                        $(next).hide();
                    }

                    position ++;

                    $(container_image).hide();
                }
                
                $(container_count).text(position+1);
                $(container_image+':nth-child('+(position)+') img').removeClass('this');
                $(container_image+':nth-child('+(position+1)+') img').addClass('this');
                $(container_image+':nth-child('+(position+1)+')').show();
                
                img_fullscreen(fullscreen);
                
                /*if(fullscreen){positions();}
                sizes(settings.style.width, settings.style.height);*/
            });
            
            //MENU
            $(menu_toggle).bind('click', function (){
                $(menu_menu).toggle();
            });
        }).fail(function (){
            alert('Impossibile aprire l\'album selezionato.')
        });
    }
    
    /*=========================================
     * AVVIARE E VISUALIZZARE IL NUOVO ALBUM
    =========================================*/
    function getAlbum(username, album, settings, gallery){
        size                    = 0;
        fullscreen              = (settings.style.fullscreen==true)?true:false;
        var protocol            = document.location.protocol == 'http:' ? 'http:' : 'https:';
        var start               = (settings.start==0)?0:settings.start;
        var position            = start;
        var img_width           = 0;
        var imgContainer_width  = 0;
        
        //var album = settings.picasa.album;
        var url = protocol + '//picasaweb.google.com/data/feed/api/user/' + username + '/album/' + album + '?kind=photo&alt=json';
        
        $.ajax({
            dataType : 'json',
            url      : url,
            data     : 'callback=?',
            async    : false
        }).done(function (json){
            $(container).replaceWith(gallery);
            
            $("#gioiagallery .title").text(json.feed.title.$t);
            
            //Immagini
            for(i = 0; i < json.feed.entry.length; i++) {
                var summary = json.feed.entry[i].summary.$t;
                var img_src = json.feed.entry[i].content.src.split('/');
                var img_filename = img_src.pop();
                var img_src = img_src.join('/');
                var screen_width = $(window).width();
                
                html =  "<div>"+
                            "<img "+
                            " src='"+
                            img_src+'/s'+img_filename+
                            "'"+
                            " />"+
                            "</div>";
                
                size ++;
                
                $(container_images).append(html);
            }
            
            $(container_image).hide();
            $(container_image+':nth-child('+(position+1)+')').show();
            $(container_image+':nth-child('+(position+1)+') img').addClass('this');

            
            //Aggiungo a video il numero dell'immagine visualizzata e il numero totale
            $(container_count).text(position+1);
            $(container_size).text(size);
            
            //Prev
            if(position==0){$(prev).hide();}
            //Next
            if(position==size-1){$(next).hide();}
            
            img_fullscreen(fullscreen);
            
            
            
            //Aggiunta del menu
            var element = "<div class='toggle'>"+
                    "<div></div>"+
                    "<div></div>"+
                    "<div></div>"+
                    "</div>"+
                    
                    "<div class='menu'></div>";
            $('.menu',container).append(element).css({
                /*position : 'absolute',
                top      : '10px',
                right    : '10px'*/
            });
            
            
            //Aggiunta degli album come voce di menu
            var url = protocol + '//picasaweb.google.com/data/feed/api/user/' + username + '?kind=album&access=public&alt=json';
            $.getJSON(url, 'callback=?', $.proxy(function(json){
                for(var i = 0; i < json.feed.entry.length; i++) {
                    var album_title = json.feed.entry[i].title.$t;
                    var album       = json.feed.entry[i].title.$t.replace(/\'/g, "").replace(/\ /g, "").replace(/\-/g, "");
                    var album_link  = "callback=?";
                    /*var album_link = '#';
                    
                    for(var j = 0; j < json.feed.entry[i].link.length; j++) {
                        if (json.feed.entry[i].link[j].type == 'text/html'){
                            album_link = json.feed.entry[i].link[j].href;
                        }
                    }*/
                    
                    var img_src = json.feed.entry[i].media$group.media$content[0].url.split('/');
                    var img_filename = img_src.pop();
                    var img_src = img_src.join('/');
                    
                    html = "<div class='row'>"+
                                "<div class='album'>"+
                                    //"<a href='"+album_link+"'>"+album_title+"</a>"+
                                    "<a href='"+album_link+"' data-action='click' data-album='"+album+"' >"+album_title+"</a>"+
                                "</div>"+
                            "</div>";
                    
                    $(menu_menu).append(html);
                    
                    //Risolvo il problema del falso caricamento delle 
                    //immagini per il ridimensionamento
                    img_fullscreen(fullscreen);
                    
                    /*$(settings.images, container).append(
                        "<div><img src='" +
                        //img_src + '/s' + data.thumbnail_width + ( data.thumbnail_cropped ? '-c' : '' ) + '/' + img_filename +
                        img_src + '/s' + '/' + img_filename +
                        "' alt='" + json.feed.entry[i].gphoto$name.$t + "' title='" + album_title +
                        "'/><p><strong>" + album_title + "</strong></p><p>" +
                        json.feed.entry[i].gphoto$numphotos.$t +
                        ' photos' +
                        //( data.link_to_picasa ? '<a href="'+album_link+'" title="View Album on Picasa" style="position:relative;margin-left:6px;" target="_blank"><img src="chain-icon.gif" alt="chain-icon" style="margin:0;top:4px;position:relative;"/></a>' : '') +
                        '<a href="'+album_link+'" title="View Album on Picasa" style="position:relative;margin-left:6px;" target="_blank"><img src="chain-icon.gif" alt="chain-icon" style="margin:0;top:4px;position:relative;"/></a>' +
                        '</p></div> --'
                    );*/
                }
                
                
                /*======================
                 * EVENTI
                ======================*/
                //CLICK PER VISUALIZZARE IL NUOVO ALBUM
                $('[data-action=\'click\']').click(function (event){
                    event.preventDefault();
                    
                    //Richiamo il nuovo album di picasa
                    getAlbum(username, $(this).attr('data-album'), settings, gallery);
                });
            }));
            
            
            
            //CSS
            /*
            colors(settings.style.bgColor, settings.style.color);
            sizes(settings.style.width, settings.style.height);
            shadows(settings.shadow.h, settings.shadow.v, settings.shadow.color, settings.shadow.spread, settings.shadow.blur);
            */
            
            
            //PREV BUTTON
            $(prev).bind('click', function (){
                $(next).show();

                if(position != 0){
                    if(position == 1){
                        $(prev).hide();
                    }

                    position --;

                    $(container_image).hide();
                }
                
                $(container_count).text(position+1);
                $(container_image+':nth-child('+(position)+') img').removeClass('this');
                $(container_image+':nth-child('+(position+1)+') img').addClass('this');
                $(container_image+':nth-child('+(position+1)+')').show();
                
                img_fullscreen(fullscreen);
                
                /*if(fullscreen){positions();}
                sizes(settings.style.width, settings.style.height);*/
            });
            
            //NEXT BUTTON
            $(next).bind('click', function (){
                $(prev).show();

                if(position != size-1){
                    if(position == size-2){
                        $(next).hide();
                    }

                    position ++;

                    $(container_image).hide();
                }
                
                $(container_count).text(position+1);
                $(container_image+':nth-child('+(position)+') img').removeClass('this');
                $(container_image+':nth-child('+(position+1)+') img').addClass('this');
                $(container_image+':nth-child('+(position+1)+')').show();
                
                img_fullscreen(fullscreen);
                
                /*if(fullscreen){positions();}
                sizes(settings.style.width, settings.style.height);*/
            });
            
            //MENU
            $(menu_toggle).bind('click', function (){
                $(menu_menu).toggle();
            });
        }).fail(function (){
            alert('Impossibile aprire l\'album selezionato.')
        });
    }
    
    
    function img_fullscreen(fullscreen){
        if(fullscreen==true){
            var maxWidth  = $(container_images).width();
            var maxWidth  = $(container_images).width();
            var maxheight = $(container_images).height();
            var ratio     = 0;
            var width     = $("#gioiagallery .images img.this").width();
            var height    = $("#gioiagallery .images img.this").height();
            
            if($("#gioiagallery .images img.this").width() > $("#gioiagallery .images img.this").height()){
                ratio = (maxWidth/width)/1.5;
                
                $("#gioiagallery .images img.this").css("width", width*ratio);
            }else{
                ratio = (maxheight/height)/1.5;
                
                $("#gioiagallery .images img.this").css("height", height*ratio);
            }
            
            var container_images_width = $(container_images).width();
            var container_images_height = $(container_images).height();
            var top  = 0;
            var left = 0;
            
            container_img_width_this  = $("#gioiagallery .images img.this").width();
            container_img_height_this = $("#gioiagallery .images img.this").height();
            left = (container_images_width-container_img_width_this)/2;
            top  = (container_images_height-container_img_height_this)/2;

            $("#gioiagallery .images img.this").css({
                'margin-left' : left,
                'margin-top'  : top
            });
        }
    }
    
    /*===========================
     * CSS
    ===========================*/
    //Posizioni
    function positions(){
        /*$(container_images).css({
            position     : 'absolute',
            top          : (($(window).height()-15)-$(container_images).height())/2,
            left         : ($(window).width()-$(container_images).width())/2
        });
        $(container_commands).css({
            border      : '0px solid red',
            width       : $(container).width(),
            position    : 'absolute',
            bottom      : '15px'
        });
        $(container_size).parent().css({
            position    : 'absolute',
            bottom      : '15px',
            left        : ($(window).width()-$(container_size).parent().width())/2
        });
        $('img', container_images).css({
            'margin-top' : '10px'
        });*/
    }
    //Dimensioni
    function sizes(width, height){
        /*$(container_images).css({
            width           : width,
            margin          : '0 auto',
            'margin-top'    : '25px'
        });*/
        $('img', container_images).css({
            //width : ($(this).width()<$(container_images))?'2px':'100px'
            width : ($(this).width()>$(container_image).width())?($(this).height()<$(container_image).height())?'100px':(($(container_image).height())-10):'5px'
            /*width  : '100%',
            height : '100%'*/
        });
    }
    //Colori dei CSS
    function colors(bgColor, color){
        //Colori
        $(container).css({
            'background-color'  : bgColor,
            'color'             : color
        });
        $(container_count).css({
            'background-color'  : bgColor,
            'color'             : color
        });
    }
    //Ombre CSS
    function shadows(h, v, color, spread, blur){
        $('img', container_images).css({
            'box-shadow' : '0px 0px 5px 5px red'
        });
    }
    
    //Plugin
    $.fn.photogallery = function( options ) {
        //Parametri di configurazione del plugin di default
        var defaults = {
            style : {
                bgColor : 'rgba(0, 0, 0, .9)',
                color   : 'white',
                size    : {
                    width  : '60%',
                    height : 'auto'
                }
            },
            position  : 'center',
            thumbnail : {
                show     : false,
                position : 'center',
                name     : 'thumbnail'
            },
            shadow      : {
                color   : 'red',
                h       : '0',
                v       : '0',
                spread  : '10px',
                blur    : '10px'
            }
        };
        var settings = $.extend({}, defaults, options );
        
        var html  = null;
        
        
        if(settings.type=='picasa'){
            //Restituisco le immagini
            picasa(settings.picasa.username, settings.picasa.album, settings, gallery, this);
        }
    };
})( jQuery );